﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;
using System.Data;

namespace iLangl.BusinessModel.DAL.XMLStorage
{
	public class LanguageDAL : BaseStorageDAL, ILanguageDAL
	{
		#region ILanguageDAL Members

		public void RegisterLanguages(IList<Model.Language> languages, IDbTransaction trans)
		{
			foreach (Language language in languages)
			{
				dtoXmlStorage.LanguageRow lr = Storage.Language.FindByCode(language.LanguageId);

				bool isnew = (lr == null);

				if (isnew)
				{
					lr = Storage.Language.NewLanguageRow();
				}

				lr.Code = language.LanguageId;
				lr.Name = language.LanguageName;

				if (isnew)
				{
					Storage.Language.AddLanguageRow(lr);
				}
			}

			if (trans == null)
			{
				AcceptChanges();
			}
		}



		public Language ReadLanguage(string code)
		{
			dtoXmlStorage.LanguageRow lr =  Storage.Language.FindByCode(code);

			if (lr == null)
				return null;

			Language result = new Language(lr.Code, lr.Name);
			return result;

		}

		public IList<Language> GetLanguages()
		{
			List<Language> result = new List<Language>();

			foreach (dtoXmlStorage.LanguageRow lr in Storage.Language)
			{
				result.Add(new Language(lr.Code, lr.Name));
			}

			return result;
		}


		public void RegisterPluginLanguages(IList<PluginLanguage> languages, IDbTransaction trans)
		{
			foreach (PluginLanguage plang in languages)
			{
				dtoXmlStorage.PluginLanguageRow plr = Storage.PluginLanguage.FindByPluginIdPluginCode(plang.PluginId, plang.PluginCode);

				bool isNew = (plr == null);
				if (isNew)
				{
					plr = Storage.PluginLanguage.NewPluginLanguageRow();
				}

				plr.PluginId = plang.PluginId;
				plr.PluginCode = plang.PluginCode;
				plr.PluginName = plang.PluginName;
				plr.LanguageCode = plang.LanguageId;

				if (isNew)
				{
					Storage.PluginLanguage.AddPluginLanguageRow(plr);
				}

				
			}

			if (trans == null)
				AcceptChanges();
		}

		public Language GetLanguage(string pluginId, string plugincode)
		{
			dtoXmlStorage.PluginLanguageRow plr = Storage.PluginLanguage.FindByPluginIdPluginCode(pluginId, plugincode);

			if(plr == null)
				return null;

			return ReadLanguage(plr.LanguageCode);
		}

		public Language GetPluginLanguage(string pluginId, string languagecode)
		{
			foreach (dtoXmlStorage.PluginLanguageRow plr in Storage.PluginLanguage)
			{
				if((plr.PluginId == pluginId)&&(plr.LanguageCode == languagecode))
				{
					return new Language(plr.PluginCode, plr.PluginName);
				}
			}

			return null;
		}

		#endregion



	}
}
